package com.gitee.wsl.platform.thread.task.bean

import com.gitee.wsl.platform.concurrent.api.Cancellable
import java.util.concurrent.CompletableFuture
import java.util.function.Function


/**
 * This is a wrapper around a [CompletableFuture] with a
 * [Cancellable] reference attached.
 *
 *
 * A standard Java [CompletableFuture] is not connected to its
 * asynchronous task and cannot be cancelled. Thus, if we want to cancel
 * a task, we need to keep a reference to a [Cancellable] object that
 * can do the job.
 *
 *
 * `CancellableFuture` is similar to [Fiber], which should
 * be preferred because it's more principled. `CancellableFuture`
 * is useful more for interoperability with Java code.
 */
@JvmRecord
data class CancellableFuture<T>(
    val future: CompletableFuture<out T>,
    val cancellable: Cancellable,
) {
    fun <U> transform(
        fn: Function<in CompletableFuture<out T>, out CompletableFuture<out U>>,
    ): CancellableFuture<U> {
        return CancellableFuture<U>(fn.apply(future), cancellable)
    }
}